#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: page_utils.py
@time: 2023/11/8 18:12
@desc: 
"""

from tornado.httputil import HTTPServerRequest

from backend.tvadmin.utils.log_utls import app_log


def pagination(data_list, page=None, page_size=None):
    """
    分页器
    :param data_list: 分页列表
    :param page: 页数
    :param page_size: 页数容量
    :return:response
    """
    if not page:
        page = 1
    else:
        page = int(page)
    if not page_size:
        page_size = 10
    else:
        page_size = int(page_size)
    start = int((page - 1) * page_size)
    end = int(start + page_size)
    items = data_list[start:end]

    # 构建分页信息
    total_items = len(data_list)
    total_pages = (total_items + page_size - 1) // page_size
    prev_page = page - 1 if page > 1 else None
    next_page = page + 1 if page < total_pages else None

    # 构建响应
    response = {
        "data": items,
        "pagination": {
            "total_items": total_items,
            "total_pages": total_pages,
            "prev_page": prev_page,
            "next_page": next_page
        }
    }
    return response


def self_pagination(request: HTTPServerRequest, data_list):
    """
    分页器
    :param data_list: 分页列表
    :param page: 页数
    :param page_size: 页数容量
    :return:response
    """
    try:
        if hasattr(request, 'data'):
            page = int(request.data.get("page")) if request.data.get("page") else 1
            page_size = int(request.data.get("page_size")) if request.data.get("page_size") else 10
        else:
            page = 1
            page_size = 10
        start = int((page - 1) * page_size)
        end = int(start + page_size)
        items = data_list[start:end]

        # 构建分页信息
        total_items = len(data_list)
        total_pages = (total_items + page_size - 1) // page_size
        prev_page = page - 1 if page > 1 else None
        next_page = page + 1 if page < total_pages else None

        # 构建响应
        response = {
            "data": items,
            "pagination": {
                "total_items": total_items,
                "total_pages": total_pages,
                "prev_page": prev_page,
                "next_page": next_page
            }
        }
        return response
    except Exception as e:
        print(e)
        app_log.error(f"error{e}")
